﻿// MedicalRulesEngine.API/Extensions/SwaggerExtensions.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using System.Reflection;

namespace MedicalRulesEngine.API.Extensions;

/// <summary>
/// Swagger配置扩展
/// </summary>
public static class SwaggerExtensions
{
    /// <summary>
    /// 添加Swagger文档生成
    /// </summary>
    /// <param name="services">服务集合</param>
    /// <returns>服务集合</returns>
    public static IServiceCollection AddSwaggerDocumentation(this IServiceCollection services)
    {
        services.AddSwaggerGen(options =>
        {
            options.SwaggerDoc("v1", new OpenApiInfo
            {
                Version = "v1",
                Title = "医疗规则引擎 API",
                Description = "基于RulesEngine的医疗规则引擎系统API文档",
                Contact = new OpenApiContact
                {
                    Name = "开发团队",
                    Email = "dev@medical-rules.com",
                    Url = new Uri("https://github.com/medical-rules-engine")
                },
                License = new OpenApiLicense
                {
                    Name = "MIT License",
                    Url = new Uri("https://opensource.org/licenses/MIT")
                }
            });

            // 包含XML注释
            var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
            var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
            if (File.Exists(xmlPath))
            {
                options.IncludeXmlComments(xmlPath);
            }

            // 添加Core项目的XML注释
            var coreXmlFile = "MedicalRulesEngine.Core.xml";
            var coreXmlPath = Path.Combine(AppContext.BaseDirectory, coreXmlFile);
            if (File.Exists(coreXmlPath))
            {
                options.IncludeXmlComments(coreXmlPath);
            }

            // 添加Domain项目的XML注释
            var domainXmlFile = "MedicalRulesEngine.Domain.xml";
            var domainXmlPath = Path.Combine(AppContext.BaseDirectory, domainXmlFile);
            if (File.Exists(domainXmlPath))
            {
                options.IncludeXmlComments(domainXmlPath);
            }

            // 配置标签
            options.TagActionsBy(api => new[] { api.GroupName ?? api.ActionDescriptor.RouteValues["controller"] });
            options.DocInclusionPredicate((name, api) => true);

            // 配置安全定义（如果需要）
            options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
            {
                Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                Name = "Authorization",
                In = ParameterLocation.Header,
                Type = SecuritySchemeType.ApiKey,
                Scheme = "Bearer"
            });

            options.AddSecurityRequirement(new OpenApiSecurityRequirement
            {
                {
                    new OpenApiSecurityScheme
                    {
                        Reference = new OpenApiReference
                        {
                            Type = ReferenceType.SecurityScheme,
                            Id = "Bearer"
                        }
                    },
                    Array.Empty<string>()
                }
            });

            // 配置示例
            options.EnableAnnotations();
            options.UseInlineDefinitionsForEnums();

            // 自定义操作ID
            options.CustomOperationIds(apiDesc =>
            {
                var actionName = apiDesc.ActionDescriptor.RouteValues["action"];
                var controllerName = apiDesc.ActionDescriptor.RouteValues["controller"];
                return $"{controllerName}_{actionName}";
            });
        });

        return services;
    }

    /// <summary>
    /// 使用Swagger UI
    /// </summary>
    /// <param name="app">应用程序构建器</param>
    /// <param name="isDevelopment">是否为开发环境</param>
    /// <returns>应用程序构建器</returns>
    public static IApplicationBuilder UseSwaggerDocumentation(this IApplicationBuilder app, bool isDevelopment = true)
    {
        if (isDevelopment)
        {
            app.UseSwagger(options =>
            {
                options.RouteTemplate = "api-docs/{documentName}/swagger.json";
            });

            app.UseSwaggerUI(options =>
            {
                options.SwaggerEndpoint("/api-docs/v1/swagger.json", "医疗规则引擎 API v1");
                options.RoutePrefix = "api-docs";
                options.DocumentTitle = "医疗规则引擎 API 文档";

                // 自定义CSS
                options.InjectStylesheet("/swagger-ui/custom.css");

                // 配置UI选项
                options.DefaultModelsExpandDepth(2);
                options.DefaultModelRendering(Swashbuckle.AspNetCore.SwaggerUI.ModelRendering.Example);
                options.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.None);
                options.EnableDeepLinking();
                options.DisplayOperationId();
                options.DisplayRequestDuration();

                // 配置OAuth（如果需要）
                options.OAuthClientId("swagger-ui");
                options.OAuthAppName("医疗规则引擎 API");
                options.OAuthUsePkce();
            });
        }

        return app;
    }
}
